/*
 Xern Entity Relocation Network
 Copyright (C) 2011 Ronie Salgado <roniesalg@gmail.com>

 Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated documentation files (the "Software"), to deal
 in the Software without restriction, including without limitation the rights
 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the Software is
 furnished to do so, subject to the following conditions:

 The above copyright notice and this permission notice shall be included in
 all copies or substantial portions of the Software.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 THE SOFTWARE.
*/

#include "HttpClient.hpp"
#include <stdio.h>
#include <boost/bind.hpp>
#include <sstream>

namespace XernMetaverse
{
    // HttpRequest
    HttpRequest::HttpRequest()
    {
        method = RM_GET;
        isSecure = false;
        postDataLen = 0;
        responseHandler = NULL;
    }

    void HttpRequest::StoreRequest(std::ostream &out) const
    {
        std::string methodName = "GET";
        switch(method)
        {
        case RM_GET:
            methodName = "GET";
            break;
        case RM_POST:
            methodName = "POST";
            break;
        }

        out << methodName << " " << resource << " HTTP/1.1\r\n" ;
        out << "Host: " << hostname << "\r\n";
        AttributesType::const_iterator it = attributes.begin();
        for(; it != attributes.end(); it++)
        {
            out << it->first << ": " << it->second << "\r\n";
        }

        // Store the content length.
        if(method == RM_POST)
            out << "Content-Length: " << postDataLen << "\r\n";

        // Finish the header.
        out << "\r\n";

        // Store the post data.
        if(method == RM_POST)
            out.write((const char*)postData.get(), postDataLen);
    }

    // HttpResponse
    HttpResponse::HttpResponse()
    {
        statusCode = ResponseNotFound;
        payloadLen = 0;
    }

    // HttpClient
    HttpClient::HttpClient()
        : socket(ioService)
    {
        boost::thread t(boost::bind(&HttpClient::ClientThread, this));
        clientThread.swap(t);
    }

    HttpClient::~HttpClient()
    {
        // Stop the I/O service.
        ioService.stop();

        // Wait the client thread to end.
        clientThread.join();
    }

    void HttpClient::Request(boost::shared_ptr<HttpRequest> request)
    {
        boost::unique_lock<boost::mutex> lock(clientMutex);

        // If there isn't a current request start it immediately
        if(!currentRequest)
        {
            StartRequest(request);
        }
        else
        {
            // Add the request into the queue.
            requestQueue.push_back(request);
            newRequestCondition.notify_one();
        }
    }

    void HttpClient::StartRequest(boost::shared_ptr<HttpRequest> request)
    {
        currentRequest = request;

        // Parse the request url.
        // protocol://host:port/resource
        const std::string &url = request->url;

        // Read the protocol.
        size_t pos = url.find("://");
        std::string protocol = url.substr(0, pos);
        pos += 3;

        // Check the protocol.
        if(protocol == "https")
            request->isSecure = true;
        else if(protocol != "http")
            throw HttpException("Invalid http url.");

        // Read the host.
        size_t spos = pos;
        pos = url.find("/", spos);
        std::string host = url.substr(spos, pos - spos);

        // Read the resource
        std::string resource = "/";
        if(pos != std::string::npos)
        	resource = url.substr(pos);

        // Read the port, if avaiable
        std::string port = "80";
        size_t portPos = host.find(":");
        if(portPos != std::string::npos)
        {
            port = host.substr(portPos+1);
            host = host.substr(0, portPos);
        }

        // If the resource is not available, set it to the root.
        if(resource.empty())
            resource = "/";

        // Resolve the host.
        tcp::resolver::query query(host, port);
        tcp::resolver resolver(ioService);
        tcp::resolver::iterator it = resolver.resolve(query);
        tcp::resolver::iterator end;

        // Try each endpoint until we successfully establish a connection.
        boost::system::error_code error = boost::asio::error::host_not_found;
        while(error && it != end)
        {
            tcp::endpoint endpoint = *it++;
            if(lastEndpoint != endpoint || !socket.is_open())
            {
                socket.close();
                socket.connect(endpoint, error);
                lastEndpoint = endpoint;
            }
        }

        // Store the host name and the endpoint.
        request->hostname = host;
        request->endpoint = lastEndpoint;

        // Store the url data in the request.
        request->resource = resource;

        // Discard the read buffer data.
        std::istream in(&responseBuffer);
        in.ignore();

        // Store the request.
        std::ostream out(&requestBuffer);
        std::ostringstream sout;
        request->StoreRequest(out);
        request->StoreRequest(sout);

        // Perform the request.
        boost::asio::async_write(socket, requestBuffer,
            boost::bind(&HttpClient::OnSentRequest, this,
                        boost::asio::placeholders::error));
    }

    void HttpClient::OnSentRequest(const boost::system::error_code &error)
    {
        boost::unique_lock<boost::mutex> lock(clientMutex);

        if(!error)
        {
            // Create the response.
            currentResponse = boost::shared_ptr<HttpResponse> (new HttpResponse());

            // Start reading the first response line
            boost::asio::async_read_until(socket, responseBuffer, "\r\n",
                boost::bind(&HttpClient::OnResponseHeaderLine, this,
                        boost::asio::placeholders::error,
                        boost::asio::placeholders::bytes_transferred));
        }
        else
        {
            if(currentRequest->responseHandler)
            {
                currentRequest->responseHandler->OnHttpFailure(error);
            }
            else
            {
                fprintf(stderr, "Failed to send the http request: %s.\n", error.message().c_str());

                // Close the socket.
                socket.close();

                // Start the next request.
                BeginNextRequest();
            }
        }
    }

    void HttpClient::OnResponseHeaderLine(const boost::system::error_code &error, size_t transferred)
    {
        boost::unique_lock<boost::mutex> lock(clientMutex);

        if(!error)
        {
            std::istream in(&responseBuffer);
            std::string protocol, message;
            std::string line;
            int statusCode;
            in >> protocol >> statusCode >> message;
            std::getline(in, line); // Ignore the "\r\n"

            //printf("response header: %s %d %s\n", protocol.c_str(), statusCode, message.c_str());
            // Store the header line data
            currentResponse->protocol = protocol;
            currentResponse->statusCode = statusCode;
            currentResponse->statusMessage = message;
            currentResponse->resource = currentRequest->resource;

            // Read the remaining part of the header.
            boost::asio::async_read_until(socket, responseBuffer, "\r\n\r\n",
                boost::bind(&HttpClient::OnResponseHeader, this,
                        boost::asio::placeholders::error,
                        boost::asio::placeholders::bytes_transferred));
        }
        else
        {
            if(currentRequest->responseHandler)
            {
                currentRequest->responseHandler->OnHttpFailure(error);
            }
            else
            {
                fprintf(stderr, "Failed to receive the first http header line.\n");
            }

            // Close the socket.
            socket.close();

            // Start the next request.
            BeginNextRequest();
        }
    }

    void HttpClient::OnResponseHeader(const boost::system::error_code &error, size_t transferred)
    {
        boost::unique_lock<boost::mutex> lock(clientMutex);

        if(!error)
        {
            std::istream in(&responseBuffer);
            std::string line;
            while(!in.eof())
            {
                // Retrieve a line.
                std::getline(in, line);

                // Ignore empty lines.
                if(line.empty() || line == "\r")
                    continue;

                // Split the line.
                size_t pos = line.find(":");
                std::string attrName = line.substr(0, pos);
                pos += 2; // Skip the ": ".

                std::string attrValue = line.substr(pos, line.find("\r") - pos); // Eliminate the "\r"

                // Store the attribute.
                currentResponse->attributes.insert(std::make_pair(attrName, attrValue));
            }

            // Search the content length.
            HttpResponse::AttributesType::const_iterator clf = currentResponse->attributes.find("Content-Length");
            if(clf == currentResponse->attributes.end())
            {
                printf("Unsupported http responses without content-length.");
                // Close the socket.
                socket.close();

                // Start the next request.
                BeginNextRequest();
            }
            else
            {
                // Read the content length.
                size_t len = atoi(clf->second.c_str());
                if(len == 0)
                {
                    // Don't read more data. Invoke the response handler.
                    if(currentRequest->responseHandler)
                    {
                        currentRequest->responseHandler->OnHttpResponse(currentResponse);
                    }
                    else
                    {
                        printf("Received empty http response.\n");
                    }

                    // Check if the connection must be closed.
                    HttpResponse::AttributesType::const_iterator ctf =
                     currentResponse->attributes.find("Connection");
                    if(ctf != currentResponse->attributes.end() && currentResponse->protocol == "HTTP/1.1" )
                    {
                        if(ctf->second == "close")
                            socket.close();
                    }
                    else if(currentResponse->protocol == "HTTP/1.0")
                    {
                        socket.close();
                    }

                    // Start the next request.
                    BeginNextRequest();
                }
                else
                {
                    // Create the buffer to hold the payload.
                    currentResponse->payload.reset(new unsigned char[len+1]);
                    currentResponse->payloadLen = len;

                    // Receive the response payload.
                    boost::asio::async_read(socket, boost::asio::buffer(currentResponse->payload.get(), len),
                        boost::bind(&HttpClient::OnResponsePayload, this,
                                boost::asio::placeholders::error,
                                boost::asio::placeholders::bytes_transferred));
                }
            }
        }
        else
        {
            if(currentRequest->responseHandler)
            {
                currentRequest->responseHandler->OnHttpFailure(error);
            }
            else
            {
                fprintf(stderr, "Failed to receive the http header.\n");
            }

            // Close the socket.
            socket.close();

            // Start the next request.
            BeginNextRequest();
        }
    }

    void HttpClient::OnResponsePayload(const boost::system::error_code &error, size_t transferred)
    {
        boost::unique_lock<boost::mutex> lock(clientMutex);

        if(!error)
        {
            // Set the extra \0. Note: the extra \0 is not included in the len.
            currentResponse->payload[currentResponse->payloadLen] = 0;

            // Call the response handler.
            if(currentRequest->responseHandler)
                currentRequest->responseHandler->OnHttpResponse(currentResponse);
            else
                printf("Received http response payload:\n%s\n", currentResponse->payload.get());

            // Check if the connection must be closed.
            HttpResponse::AttributesType::const_iterator ctf =
                currentResponse->attributes.find("Connection");
            if(ctf != currentResponse->attributes.end() && currentResponse->protocol == "HTTP/1.1" )
            {
                if(ctf->second == "close")
                    socket.close();
            }
            else if(currentResponse->protocol == "HTTP/1.0")
            {
                socket.close();
            }

            // Start the next request.
            BeginNextRequest();
        }
        else
        {
            if(currentRequest->responseHandler)
            {
                currentRequest->responseHandler->OnHttpFailure(error);
            }
            else
            {
                fprintf(stderr, "Failed to receive the http response payload.\n");
            }

            // Close the socket.
            socket.close();

            // Start the next request.
            BeginNextRequest();
        }
    }

    void HttpClient::BeginNextRequest()
    {
        // Start processing the next request.
        if(!requestQueue.empty())
        {
            currentRequest = requestQueue.front();
            requestQueue.pop_front();
            StartRequest(currentRequest);
        }
    }

    void HttpClient::CancelAllRequests()
    {
        boost::unique_lock<boost::mutex> lock(clientMutex);

        printf("Cancel all requests\n");

        // Clear the request queue.
        requestQueue.clear();

        // Stop the io service.
        ioService.stop();

        // Release the lock.
        lock.unlock();

        // Wait the client thread to end.
        clientThread.join();

        // Close the socket.
        if(socket.is_open())
        {
            // Shutdown the socket.
            socket.shutdown(tcp::socket::shutdown_both);
            socket.close();
        }

        // Restart the client thread.
        boost::thread t(boost::bind(&HttpClient::ClientThread, this));
        clientThread.swap(t);
    }

    void HttpClient::ClientThread()
    {
        boost::asio::io_service::work w(ioService);
        ioService.run();
    }

}; // namespace Xern
